package com.lichuandi.springbootdemo1.util;

/**
 * @author Lichuandi
 * @version 1.0
 * @program : springbootdemo1
 * @ClassName SnowflakeIdGenerator
 * @description :
 * @create: 2025-01-10 14:54
 **/
public class SnowflakeIdGenerator {
    private long datacenterId; // 数据中心ID
    private long machineId; // 机器ID
    private long sequence = 0L; // 序列号
    private long lastTimestamp = -1L; // 上一次时间戳
    private final long twepoch = 1288834974657L; // 时间基准点
    private final long datacenterIdBits = 5L; // 数据中心ID位数
    private final long machineIdBits = 5L; // 机器ID位数
    private final long maxDatacenterId = -1L ^ (-1L << datacenterIdBits); // 最大数据中心ID
    private final long maxMachineId = -1L ^ (-1L << machineIdBits); // 最大机器ID
    private final long sequenceBits = 12L; // 序列号位数
    private final long machineIdShift = sequenceBits; // 机器ID偏移量
    private final long datacenterIdShift = machineIdBits + sequenceBits; // 数据中心ID偏移量
    private final long timestampLeftShift = sequenceBits + machineIdBits + datacenterIdBits; // 时间戳左移位数
    private final long sequenceMask = -1L ^ (-1L << sequenceBits); // 序列号掩码

    public SnowflakeIdGenerator(long datacenterId, long machineId) {
        if (datacenterId > maxDatacenterId || datacenterId < 0) {
            throw new IllegalArgumentException("datacenterId must be between 0 and " + maxDatacenterId);
        }
        if (machineId > maxMachineId || machineId < 0) {
            throw new IllegalArgumentException("machineId must be between 0 and " + maxMachineId);
        }
        this.datacenterId = datacenterId;
        this.machineId = machineId;
    }

    public synchronized long nextId() {
        long timestamp = timeGen();

        if (timestamp < lastTimestamp) {
            throw new RuntimeException(String.format("Clock moved backwards. Refusing to generate id for %d milliseconds", lastTimestamp - timestamp));
        }

        if (lastTimestamp == timestamp) {
            sequence = (sequence + 1) & sequenceMask;
            if (sequence == 0) {
                timestamp = tilNextMillis(lastTimestamp);
            }
        } else {
            sequence = 0L;
        }

        lastTimestamp = timestamp;

        return ((timestamp - twepoch) << timestampLeftShift) |
                (datacenterId << datacenterIdShift) |
                (machineId << machineIdShift) |
                sequence;
    }

    protected long tilNextMillis(long lastTimestamp) {
        long timestamp = timeGen();
        while (timestamp <= lastTimestamp) {
            timestamp = timeGen();
        }
        return timestamp;
    }

    protected long timeGen() {
        return System.currentTimeMillis();
    }

    public static void main(String[] args) {
        SnowflakeIdGenerator idGenerator = new SnowflakeIdGenerator(1, 1);
        long id = idGenerator.nextId();
        ///1877609956136587264
        System.out.println("Generated Snowflake ID: " + id);
    }
}
